package io.renren.modules.substation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.modules.substation.dao.TInfoAreaInfoDao;
import io.renren.modules.substation.entity.TInfoAreaInfoEntity;
import io.renren.modules.substation.service.TreeAreaInfoService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监测区域信息表
 *
 * @author lan
 * @email sunlightcs@gmail.com
 * @date 2020-05-25 22:31:36
 */
@Service("treeAreaInfoService")
public class TreeAreaInfoServiceImpl  extends ServiceImpl<TInfoAreaInfoDao, TInfoAreaInfoEntity> implements TreeAreaInfoService {
    private List<TInfoAreaInfoEntity> treeList = new ArrayList<>();  //全局变量

    @Override
    public List<TInfoAreaInfoEntity> getTree() {
        //先获取到所有数据
        treeList=baseMapper.selectList(new QueryWrapper<>());
        if(treeList==null) return null;

        //获取到所有一级节点
        List<TInfoAreaInfoEntity> parentList = this.baseMapper.findParentList();
        List<TInfoAreaInfoEntity> list = new ArrayList<>();
        if(parentList != null){
            for (int i = 0; i < parentList.size(); i++) {
                list.add(recursiveTree(parentList.get(i).getAreaId()));
            }
        }
        return list;
    }

    /**
     * 递归算法解析成树形结构
     * @param cid
     */
    public TInfoAreaInfoEntity recursiveTree(Long cid) {
        TInfoAreaInfoEntity node = getAreaInfoById(cid);
        List<TInfoAreaInfoEntity> childTreeNodes  = getChildTreeById(cid);
        for(TInfoAreaInfoEntity child : childTreeNodes){
            TInfoAreaInfoEntity n = recursiveTree(child.getAreaId());
            node.getChildren().add(n);
        }
        return node;
    }

    /**
     * 根据CID查询节点对象
     */
    public TInfoAreaInfoEntity getAreaInfoById(Long cid){
        Map map =  getTreeMap();
        return (TInfoAreaInfoEntity) map.get(cid);
    }

    /**
     * 一次性取所有数据，为了减少对数据库查询操作
     * @return
     */
    public Map getTreeMap(){
        Map map =  new HashMap<Integer, TInfoAreaInfoEntity>();
        if(null != treeList){
            for(TInfoAreaInfoEntity d : treeList){
                map.put(d.getAreaId(), d);
            }
        }
        return map;
    }

    /**
     * 根据父节点CID获取所有了节点
     */
    public List<TInfoAreaInfoEntity> getChildTreeById(Long cid){
        List<TInfoAreaInfoEntity> list = new ArrayList<>();
        if(null != treeList){
            for (TInfoAreaInfoEntity d : treeList) {
                if(null != cid){
                    if (cid.equals(d.getParentAreaCode())) {
                        list.add(d);
                    }
                }
            }
        }
        return list;
    }

}
